package thread

import (
	"codejy/store"
	"codejy/structdef"
	"codejy/typedefault"
	"strconv"
	"sync"
)

type WaitGroup struct {
	Addr        string
	ThreadStore *structdef.ThreadStore
	WaitGroup   sync.WaitGroup
}

// 创建实例
func (a *WaitGroup) CreateTypeDefault(addr string, threadStore *structdef.ThreadStore, parameter ...string) {
	instance := &WaitGroup{
		Addr:        addr,
		ThreadStore: threadStore,
		WaitGroup:   sync.WaitGroup{},
	}
	//如果parameter[0] 不是“” 那么就是有参数的
	if parameter[0] != `""` {
		size, p := strconv.Atoi(parameter[0])
		if p != nil {
			panic("WaitGroup第一个参数错误,必须是整数")
		}
		instance.WaitGroup.Add(size)
	}
	store.AddTypeDefaultInstanceStore(threadStore, a.GetTypeName(), addr, instance)
}
func (a *WaitGroup) ParameterProcessing(parameter []string) []string {
	return parameter
}

func (a *WaitGroup) GetData() interface{} {
	return nil
}

func (a *WaitGroup) ToStr() string {
	return ""
}

// 增加线程数量
func (a *WaitGroup) Add(size string) {
	sizeInt, p := strconv.Atoi(size)
	if p != nil {
		panic("WaitGroup-add(?)参数错误,必须是整数")
	}
	a.WaitGroup.Add(sizeInt)
}

// 减少线程数量
func (a *WaitGroup) Done() {
	a.WaitGroup.Done()
}

// 等待线程数量为0
func (a *WaitGroup) Wait() {
	a.WaitGroup.Wait()
}

func (f *WaitGroup) GetDef() string {
	return `
		@CodeManual(def="new("WaitGroup")",des="创建等待一组线程执行完毕的监听器")
		type WaitGroup{
			def init{
				core&CreateTypeDefault($1)
			}
			@CodeManual(def="add($1)",des="增加线程数量")
			def add{
				core&Add($1)
			}

			@CodeManual(def="done()",des="减少线程数量")
			def done{
				core&Done()	
			}

			@CodeManual(def="wait()",des="等待线程数量为0")
			def wait{
				core&Wait()
			}
		}
	`
}
func init() {
	typedefault.RegisterTypeDefault(&WaitGroup{})
}

func (f *WaitGroup) GetTypeName() string {
	return "WaitGroup"
}
